package main

import (
	"embed"
	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/menu"
	"github.com/wailsapp/wails/v2/pkg/menu/keys"
	"github.com/wailsapp/wails/v2/pkg/options"
	wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
	"io/ioutil"
	"path/filepath"
	"runtime"
)

//go:embed all:frontend/dist
var assets embed.FS

func main() {

	// Create an instance of the app structure
	app := NewApp()

	AppMenu := menu.NewMenu()
	FileMenu := AppMenu.AddSubmenu("File")
	FileMenu.AddText("&Open", keys.CmdOrCtrl("o"), func(data *menu.CallbackData) {

		path, err := wailsRuntime.OpenFileDialog(app.ctx, wailsRuntime.OpenDialogOptions{
			CanCreateDirectories: true,
		})
		if err != nil {
			return
		}
		fileInfos, err := ioutil.ReadDir(path)
		if err != nil {
			return
		}
		wailsRuntime.LogInfo(app.ctx, fileInfos[0].Name())
	})
	FileMenu.AddText("&OpenFolder", keys.Shift("o"), func(data *menu.CallbackData) {

		path, err := wailsRuntime.OpenDirectoryDialog(app.ctx, wailsRuntime.OpenDialogOptions{
			CanCreateDirectories: true,
		})
		if err != nil {
			wailsRuntime.LogError(app.ctx, err.Error())
			return
		}
		fileInfos, err := ioutil.ReadDir(path)
		if err != nil {
			wailsRuntime.LogError(app.ctx, err.Error())
			return
		}
		children := make([]TreeData, 0)
		base := filepath.Base(path)
		parent := TreeData{Title: base, Key: path, IsLeaf: false}
		for _, info := range fileInfos {
			fileName := info.Name()
			filePath := path + string(filepath.Separator) + fileName
			treeData := TreeData{Title: fileName, Key: filePath, IsLeaf: true}
			if info.IsDir() {
				treeData.IsLeaf = false
				if subFiles, innerErr := ioutil.ReadDir(filePath); innerErr == nil && len(subFiles) > 0 {
					treeData.Children = make([]TreeData, 0)
				}
			}
			children = append(children, treeData)
		}
		parent.Children = children
		wailsRuntime.LogInfo(app.ctx, parent.Key)
		wailsRuntime.EventsEmit(app.ctx, "SelectedFolderEvent", parent)
	})
	FileMenu.AddSeparator()
	FileMenu.AddText("Save", keys.CmdOrCtrl("s"), func(_ *menu.CallbackData) {
		wailsRuntime.EventsEmit(app.ctx, "SaveFileContent")
	})
	FileMenu.AddSeparator()
	FileMenu.AddText("Quit", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) {
		wailsRuntime.Quit(app.ctx)
	})

	if runtime.GOOS == "darwin" {
		AppMenu.Append(menu.EditMenu()) // on macos platform, we should append EditMenu to enable Cmd+C,Cmd+V,Cmd+Z... shortcut
	}

	// Create application with options
	err := wails.Run(&options.App{
		Title:            "LBH_Markdown",
		Width:            1024,
		Height:           768,
		Assets:           assets,
		BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
		Menu:             AppMenu,
		OnStartup:        app.startup,
		Bind: []interface{}{
			app,
		},
	})

	if err != nil {
		println("Error:", err.Error())
	}
}

type TreeData struct {
	Title    string     `json:"title"`
	Key      string     `json:"key"`
	IsLeaf   bool       `json:"isLeaf"`
	Children []TreeData `json:"children"`
}
